<template>
  <div class="">
    <el-dialog
      :title="isAdd ? '添加角色' : '修改角色'"
      :visible.sync="isShow"
      center
      :before-close="cancel"
    >
      <el-form ref="roleData" :model="rolelist" :rules="rules">
        <el-form-item
          label="角色名称"
          prop="rolename"
          :label-width="formLabelWidth"
        >
          <el-input v-model="rolelist.rolename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色权限" :label-width="formLabelWidth">
          <el-tree
            ref="tree"
            :data="$store.getters['menu/getMenu']"
            show-checkbox
            default-expand-all
            node-key="id"
            :props="{
              children: 'children',
              label: 'title',
            }"
          >
          </el-tree>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="rolelist.status"
            active-color="#13ce66"
            inactive-color="gray"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="confirm" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getroleadd, roleedit, getroleinfo } from "../../request/api";
import { mapGetters, mapActions } from "vuex";
export default {
  data() {
    return {
      // rolename角色名称string
      // menus角色权限 id数组'2,3,4' 字符串
      // status状态1正常2禁用number
      rolelist: {
        rolename: "",
        menus: "",
        status: 1,
      },
      rules: {
        rolename: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
      },
      formLabelWidth: "120px",
    };
  },
  props: ["isShow", "isAdd"],
  computed: {
    ...mapGetters({
      roleForm: "menu/getRole",
    }),
  },
  mounted() {
    //触发菜单的获取数据
    //为了减少服务器压力  避免出现重复调用接口  要进行优化
    //如果用户在其它模块调用了 就不再重复调用了
    if (this.$store.getters["menu/getMenu"].length == 0) {
      this.$store.dispatch("menu/getMenuAction");
    }
  },
  methods: {
    ...mapActions({
      getRoleAction: "role/getRoleAction",
    }),
    //关闭弹框
    cancel() {
      this.reset();
      this.$emit("cancel", false);
    },
    //初始化表单数值
    reset() {
      this.form = {
        rolename: "",
        menus: "",
        status: 1,
      };
      // resetFields  对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.roleData.resetFields();
      this.$refs.tree.setCheckedKeys([]);
    },
    //点击表格的编辑按钮
    lookup(id) {
      getroleinfo({ id }).then((res) => {
        if (res.code == 200) {
          this.rolelist = res.list;
          this.rolelist.id = id;
          //编辑修改时  数据回显  menus回显的是字符串  必须再修改成数组
          this.rolelist.menus
            ? this.$refs.tree.setCheckedKeys(this.rolelist.menus.split(","))
            : this.$refs.tree.setCheckedKeys([]);
        }
      });
    },
    //表单确认事件
    confirm() {
      this.$refs.roleData.validate((val) => {
        if (val) {
          //接口要求  menus必须是字符串  所以修改后在传入
          this.rolelist.menus = this.$refs.tree.getCheckedKeys().join(",");
          if (this.isAdd) {
            getroleadd(this.rolelist)
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.msg);
                  //添加成功 关闭弹窗
                  this.cancel();
                  //重新调用获取数据
                  this.getRoleAction();
                }
              })
              .catch((res) => {
                this.$message.error(res.msg);
              });
          } else {
            roleedit(this.rolelist)
              .then((res) => {
                //编辑成功
                this.$message.success(res.msg);
                //关闭弹窗
                this.cancel();
                //重新获取数据
                this.getRoleAction();
              })
              .catch((err) => {
                this.$message.error(res.msg);
              });
          }
        }
      });
    },
  },
};
</script>
<style scoped>
</style>